package cn.libinal.scloud.base.common.utils;

import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author libinal
 */
@Log4j2
public class IpUtil {

    private static final String IPV4_LOCAL_IP = "127.0.0.1";
    private static final String IPV6_LOCAL_IP = "127.0.0.1";
    private static final Integer IP_LENGTH = 15;
    private static final String HEADER_IP_SEPARATOR = ",";

    /**
     * 获取客户端ip
     *
     * @param request HttpServletRequest
     * @return IP
     */
    public static String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (IPV4_LOCAL_IP.equals(ipAddress) || IPV6_LOCAL_IP.equals(ipAddress)) {
                InetAddress inet;
                try {
                    inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if ( ipAddress != null && ipAddress.length() > IP_LENGTH){
            if (ipAddress.indexOf(HEADER_IP_SEPARATOR) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(HEADER_IP_SEPARATOR));
            }
        }
        return ipAddress;
    }
}
